package com.junzhiit.nengji.api.web.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class URLAnalysis {
    private final Map<String, String> paramMap = new HashMap<String, String>();

    public void analysis(String url) {
        paramMap.clear();
        if (!"".equals(url)) {// 如果URL不是空字符串
            if (url.toLowerCase(Locale.ENGLISH).startsWith("http") || url.toLowerCase(Locale.ENGLISH).startsWith("https")) {
                url = url.substring(url.indexOf('?') + 1);
            }
            final String[] paramaters = url.split("&");
            for (final String param : paramaters) {
                final String[] values = param.split("=");
                if (values.length == 2) {
                    paramMap.put(values[0], values[1]);
                } else {
                    paramMap.put(values[0], "");
                }
            }
        }
    }

    public String getParam(final String name) {
        try {
            if (paramMap.get(name) == null) {
                return null;
            } else {
                return URLDecoder.decode(paramMap.get(name), Constants.UTF8);
            }
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
            return "";
        }
    }
}
